package py.edu.uaa.jpizzeria;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class JPizzeriaServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		proccess(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		proccess(req, resp);
	}

	void proccess(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String cliente = req.getParameter("cliente"); 
		String direccion = req.getParameter("direccion"); 
		String detalles = req.getParameter("detalles"); 
		
		System.out.println(cliente);
		System.out.println(direccion);
		System.out.println(detalles);
		
		//resp.setContentType("text/plain");
		//resp.getWriter().println(cliente);
		//resp.getWriter().println(direccion);
		//resp.getWriter().println(detalles);

		Pedido pedido = new Pedido(cliente, direccion);
		
		System.out.println(pedido.getId());
		for(String item : detalles.split(",")){
			String producto = item.split("\\|")[0];
			int precio = Integer.parseInt(item.split("\\|")[1]);
			int cantidad = 1;
			Detalle detalle = new Detalle(pedido, producto, precio, cantidad);	
			pedido.getDetalles().add(detalle);
		}
			
		EntityManager em = EMF.get().createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			em.persist(pedido);
			tx.commit();
	    } finally {
	    	if(tx.isActive()) {
	    		tx.rollback();
	    	}
	        em.close();
	    }
	    resp.sendRedirect("order.jsp");		
	}

}
